//
//  ProductListController.m
//  FinancialProduct
//
//  Created by Stella on 2017/8/24.
//  Copyright © 2017年 maq. All rights reserved.
//
#import "ProductListCell.h"
#import "HandleNetProduct.h"
#import "ProductListController.h"
#import "MJRefresh.h"
#import "CKPuslichTool.h"
#import "SearchController.h"
#import "ProductModel.h"
#import "UserModel.h"
#import "NeedPersionalController.h"
#import "bottomLabelCell.h"
#import "RenZProgressController.h"
#import "RegularViewController.h"
#import "MakeAppointmentController.h"
#import "ProductDetailController.h"
#import "ProductDetailLineController.h"
#import "NewProductDetController.h"
#import "NewProductDetLineController.h"

@interface ProductListController (){
    int count;
    BOOL isBottom;
}
@property (weak, nonatomic) IBOutlet UITableView *mTableView;
@property(strong,nonatomic)NSString *ProductType;
@property(strong,nonatomic)NSString *ProductName;
@property(strong,nonatomic)NSString *MoneyTypes;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableBottomH;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIButton *SearchButton;
@property (weak, nonatomic) IBOutlet UIView *noDataView;
@property(strong,nonatomic)NSMutableArray *dataArray;
@end
static BOOL isReLoad=YES;

@implementation ProductListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"在售产品";
    self.ProductType=@"";
    self.ProductName=@"";
    self.MoneyTypes=@"RMB";
    self.dataArray=[[NSMutableArray alloc] init];
    self.mTableView.estimatedRowHeight=140;
    self.tableBottomH.constant=0;
    self.bottomView.hidden=YES;
    isBottom=NO;
    self.mTableView.rowHeight = UITableViewAutomaticDimension;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadMyList)
                                                 name:@"RELOADMYLIST"
                                               object:nil];
    
    _mTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        count=1;
        [self getlistDataArray];
    }];
    _mTableView.mj_footer =[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        count++;
        [self getlistDataArray];
    }];
    
    [self.SearchButton setTitle:@"分类搜索" forState:UIControlStateNormal];
    [self.SearchButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

    count=1;
    [self checkRealNameConfirm];

}

- (void)checkRealNameConfirm{
    if ([[UserModel getUser].Accountstatus integerValue]==1) {
        [self getlistDataArray];
        return;
    }
    [HandleNetProduct getUserIDConfirmStatusForAccountPhone:[UserModel getUser].Phone Success:^(NSDictionary *data) {
        if ([data[@"IDConfirm"] isEqualToString:@"完成"] && [data[@"InvestorConfirm"] isEqualToString:@"完成"]) {
            [self getlistDataArray];
            return ;
        }else{
            //没有实名认证的提示
            NeedPersionalController *vc = (NeedPersionalController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"NeedPersionalController"];
            [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
            [vc setModalPresentationStyle:UIModalPresentationOverFullScreen];
            vc.returnBlock = ^{
                [self goRenzProgress:data];
            };
            vc.returnBackBlock = ^{
                NSDictionary *dic=@{@"index":@"0"};
                [[NSNotificationCenter defaultCenter]postNotificationName:@"goToOtherView" object:nil userInfo:dic];

            };
            [self presentViewController:vc animated:YES completion:nil];
        }
        
    } Failure:^(NSString *errorInfo) {
        
    }];
}

- (void)goRenzProgress:(NSDictionary *)dic{
    RenZProgressController *vc = (RenZProgressController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Setting" viewID:@"RenZProgressController"];
//    vc.dataDic = dic;
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)reloadMyList{
    self.ProductType=@"";
    self.ProductName=@"";
    self.MoneyTypes=@"RMB";
    [self.SearchButton setTitle:@"分类搜索" forState:UIControlStateNormal];
    [self.SearchButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self removeListAndReload];
    
    
    
}
-(void)removeListAndReload{
    [_dataArray removeAllObjects];
    [_mTableView reloadData];
    count=1;
    [self checkRealNameConfirm];
    
    
}
-(IBAction)rightButton:(UIButton *)barBt{
    [self.SearchButton setTitle:@"分类搜索" forState:UIControlStateNormal];
    [self.SearchButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    //去搜索页面
    SearchController *vc=(SearchController *)[CKPuslichTool getViewControllerFromStroyBoard:@"My" viewID:@"SearchController"];
    vc.returnSearchContent = ^(NSString *searchContent) {
        self.ProductName=searchContent;
        self.ProductType=@"";
        _MoneyTypes=@"RMB";
        [self.SearchButton setTitle:searchContent forState:UIControlStateNormal];
        [self.SearchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self removeListAndReload];
    };
    
    vc.returnCategory = ^(NSUInteger index) {
        NSString *textName;
        //A 现金管理类  B 固定收益类  C 一级市场 D 二级市场
        switch (index) {
            case 0:
            {
                self.ProductType=@"";
                textName=@"全部";
            }
                break;
            case 1:
            {
                self.ProductType=@"A";
                textName=@"现金管理";
            }
                break;
            case 2:
            {
                self.ProductType=@"B";
                textName=@"固收/类固收";
            }
                break;
            case 3:
            {
                self.ProductType=@"C";
                textName=@"一级市场";
            }
                break;
            case 4:
            {
                self.ProductType=@"D";
                textName=@"二级市场";
            }
                break;
                
            default:
                break;
        }
        self.ProductName=@"";
        _MoneyTypes=@"RMB";
//        [self.SearchButton setTitle:textName forState:UIControlStateNormal];
//        [self.SearchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self removeListAndReload];
    };
    vc.returnMoneyType = ^(NSString *moneyType) {
        if ([moneyType isEqualToString:@"人民币"]) {
            self.MoneyTypes=@"RMB";
            
        }else{
            self.MoneyTypes=@"USD";
        }
        self.ProductType=@"";
        self.ProductName=@"";
        [self removeListAndReload];
    };
    [self.navigationController pushViewController:vc animated:YES];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];


}
-(void)getlistDataArray{
    UserModel *model=[UserModel getUser];

    if (isBottom&&count>1) {
        [self.mTableView.mj_header endRefreshing];
        [self.mTableView.mj_footer endRefreshing];
        return;
    }
    int mid=[model.CustomerID intValue];
    NSDictionary *params=@{@"AAAMethodName":@"ProSalelist",@"CustomerID":@(mid),
                           @"PageIndex":@(count),
                           @"PageSize":@(20),
                           @"SubProductName":self.ProductName,
                           @"CurrencyType":self.MoneyTypes,
                           @"ProductTypeLevel":self.ProductType,
                           @"Accountstatus":model.Accountstatus
                           };
    [HandleNetProduct getListforParams:params Success:^(NSArray *data) {
        [self.mTableView.mj_header endRefreshing];
        [self.mTableView.mj_footer endRefreshing];
        if (count==1) {
            [self.dataArray removeAllObjects];
        }
        if (data.count>0) {
            
            [self.dataArray addObjectsFromArray:data];
            isBottom=NO;
        }else{
            isBottom=YES;
//            self.totalLabel.text=[NSString stringWithFormat:@"已到底部，共加载%d条信息",(int)self.dataArray.count];
//            self.tableBottomH.constant=60;
//            self.bottomView.hidden=NO;
        }
        
        if (self.dataArray.count>0) {
            self.noDataView.hidden=YES;
        }else{
            self.noDataView.hidden=NO;
        }
        [self.mTableView reloadData];

    } Failure:^(NSString *errorInfo) {
        [self.mTableView.mj_header endRefreshing];
        [self.mTableView.mj_footer endRefreshing];
    }];
   
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    
//    
//    
//    NSIndexPath *path =  [self.mTableView indexPathForRowAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
//
//    if (self.dataArray.count-4==path.section) {
//        return;
//    }
//    self.bottomView.hidden=YES;
//    
//}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (isBottom) {
        return self.dataArray.count+1;
    }
    return self.dataArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==self.dataArray.count) {
        bottomLabelCell *cell=[tableView dequeueReusableCellWithIdentifier:@"bottomLabelCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryNone;
        cell.backgroundColor=[UIColor clearColor];
        cell.totalLabel.text=[NSString stringWithFormat:@"已到底部，共加载%d条信息",(int)self.dataArray.count];
        return cell;
    }
    NSDictionary *dic=self.dataArray[indexPath.section];
    NSString *cellID;
    if ([dic[@"ProductTypeLevel1"] isEqualToString:@"一级市场"]) {
        cellID=@"ProductListCellC";
    }else if ([dic[@"ProductTypeLevel1"] isEqualToString:@"二级市场"]) {
        cellID=@"ProductListCellD";
    }else{
        cellID=@"ProductListCellA";
    }
    ProductListCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryNone;
    ProductModel *mode=[ProductModel mj_objectWithKeyValues:dic];
    cell.productModel=mode;
   
    [cell layoutIfNeeded];
    return cell;
    

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==self.dataArray.count) {
        return;
    }
    //现金管理、固收
    NSDictionary *dic=self.dataArray[indexPath.section];
    ProductModel *mode=[ProductModel mj_objectWithKeyValues:dic];
//    if ([mode.ProductTypeLevel1 isEqualToString:@"现金管理类"]||[mode.ProductTypeLevel1 isEqualToString:@"固收"]) {
//        ProductDetailController *vc=(ProductDetailController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"ProductDetailController"];
//        vc.productModel=mode;
//        [self.navigationController pushViewController:vc animated:YES];
//    }else{
//        
//        ProductDetailLineController *vc=(ProductDetailLineController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"ProductDetailLineController"];
//        vc.productModel=mode;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    NSString *cateNa =  mode.ProductTypeLevel1;
    NSLog(@"产品类型==%@",cateNa);
    [self getdetailWith:mode.SubProductID productTypeLevel1:cateNa];

}
-(void)getdetailWith:(NSString *)subid productTypeLevel1:(NSString *)productType{
//    isReLoad=NO;
    NSDictionary *params=@{@"AAAMethodName":@"ProductDetail",@"SubProductId":subid};
    [HandleNetProduct getDetailForParams:params Success:^(NSDictionary *data) {
        ProductDetail *mode=[ProductDetail mj_objectWithKeyValues:data];
        if ([mode.ProductType isEqualToString:@"A"]||[mode.ProductType isEqualToString:@"B"]) {
//            ProductDetailController *vc=(ProductDetailController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"ProductDetailController"];
//            vc.productModel=mode;
//            vc.productId=subid;
//
//            [self.navigationController pushViewController:vc animated:YES];
            NewProductDetController *vc=(NewProductDetController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"NewProductDetController"];
            vc.productModel=mode;
            vc.productId=subid;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            
//            ProductDetailLineController *vc=(ProductDetailLineController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"ProductDetailLineController"];
//            vc.productModel=mode;
//            vc.productId=subid;
//            vc.productTypeLevel1=productType;
//            [self.navigationController pushViewController:vc animated:YES];
            NewProductDetLineController *vc=(NewProductDetLineController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"NewProductDetLineController"];
            vc.productModel=mode;
            vc.productId=subid;
            vc.productTypeLevel1=productType;
            [self.navigationController pushViewController:vc animated:YES];
        }

    } Failure:^(NSString *errorInfo) {
        
    }];


}

@end
